/**
 * Created by Administrator on 2017/6/8 0008.
 */

//import {runSqlInfo} from '../common/dataAccess';
var db = require('../common/dataAccess');
var fs = require('fs');
/**
 * 登入
 * @param parame
 * @param req
 * @param cb
 */
exports.doLogin = function(parame, req,cb){
    var form = parame;
    console.log("formis :",form);
    var obj = {};
    var account = form.account.toLowerCase();
    var password = form.password;
    obj.commands = " SELECT * from plateuser WHERE account = '" + account + "' and password = '" + password + "'";

    db.runSqlInfo(obj, function (info, err) {
        if (err) {
            jsonStr = JSON.stringify({code:500, msg:'用户名或密码不正确!'});
            cb (jsonStr);
        }
        else {
            if(info.length <= 0 ){
                jsonStr = {code:500, msg:'用户名或密码不正确!'};
                return cb (jsonStr);
            }
            console.log("ifno is",info)
            var userInfo = info[0];
            req.session.user = {};
            req.session.user.username = userInfo.account;
            req.session.user.isAdmin = userInfo.role;
            req.session.user.password = password;
            req.session.user.power = JSON.parse(userInfo.power);
            req.session.system = global.system;

            console.log("req.session.user.power",req.session.user.power)
         /*   if(req.session.user.power.appid.length < 0){
                var errInfo =  {code:500,msg:"没有产品权限请联系管理员"}
                return  cb (jsonStr);
            }*/

            if(req.session.user.isAdmin == 1 ){
                req.session.user.app_id = 0
            }
            var loginip = req.headers['x-forwarded-for'] ||
                req.connection.remoteAddress ||
                req.socket.remoteAddress ||
                req.connection.socket.remoteAddress;

            var loginip = loginip.split(":");
            loginip = loginip[loginip.length - 1];
            req.session.user.topInfo = fs.readFileSync('../views/boss/top.html','utf-8');
            req.session.user.menu = fs.readFileSync('../views/boss/menu.html','utf-8');
            //fs.appendFileSync('./logs/loginLog/loginInfo.log', "\r\n" + JSON.stringify({account:form.account,ip:loginip}) + ",",null,2);
            var jsonStr ={code:200, msg:'操作成功!',isAdmin:req.session.user.isAdmin};
            cb(jsonStr);
        }
    });
};


/**
 * 退出登入
 * @param parame
 * @param req
 * @param cb
 */
exports.logout = function (parame, req,cb){
    req.session.user = null;
    req.session.serverId = null;
    req.session.error = null;
    req.session.system = null;
    req.session.destroy();
    cb()

};
